﻿using ImageManager.Common;
using ImageManager.Model;
using ImageManager.MyType;
using System.Reflection;

namespace ImageManager.DBAccess.AOP
{
    public class ForeignCheckAction<T> : IBeforeSaveAction<T> where T : BaseModel, new()
    {
        public void Handle(BeforeSaveEventArgs<T> arg)
        {
            foreach (var prop in typeof(T).GetProperties())
            {
                var errMsg = Handle4Prop(arg, prop);
                if (!String.IsNullOrWhiteSpace(errMsg))
                {
                    arg.Cancle = true;
                    arg.Message = errMsg;
                    return;
                }
            }
        }
        protected string Handle4Prop(BeforeSaveEventArgs<T> arg, PropertyInfo prop)
        {
            var foreignAttr = prop.GetCustomAttribute<MyForeignAttribute>();
            if (foreignAttr == null) return "";
                var val = prop.GetValue(arg.Data);
            if (val == null)
            {
                return "";
            }

            var pkField = nameof(BaseModel.Pk);
            var instance = ServiceLoader.GetService<DbInstance>();
            DbFuzzyQuery fuzzyQry = new DbFuzzyQuery(instance, foreignAttr.RefType);
            var refPk = fuzzyQry.Where(CondCollection.True().Eq(pkField, val.ToString())).First();
            if (refPk==null)
            {
                return String.Format("找不到{0}对应的档案",val.ToString());
            }
            return "";
        }
    }
}
